import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonService } from 'src/app/service/common/common.service';
import { LoginService } from 'src/app/service/login.service';
import { MessageService } from 'src/app/service/message.service';
import { UserInfoData, UserInfoService } from 'src/app/service/user-info/user-info.service';
import { getStorage, removeStorage } from 'src/app/utils/storage';
import { formValid } from '../../utils/form-valid';
import { debugLog } from '../../utils/log';
import { PHONE_REG } from '../../utils/regExp';
import { encryptPwd, slRun_t } from '../../utils/utils';
import { environment } from 'src/environments/environment';
import { appConfig } from 'src/app/config/app-config';

enum LoginTypeEnum {
  PASSWORD,
  VERIFY_CODE,
  WE_CHAT,
  ZHI_FU_BAO
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  logo = appConfig.LOGO_BLACK

  submitLoading = false
  redirectUrl = '/me'
  redirectParams = null
  constructor(
    private router: Router,
    private loginService: LoginService,
    private message: MessageService,
    private userInfoService: UserInfoService,
    private commonService: CommonService,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    if(this.userInfoService.getIsLogin()){
      this.router.navigate(['/me'])
      return
    }
    this.route.queryParams.subscribe((res: any) => {
      this.redirectUrl = res.redirect_url ? res.redirect_url : '/me'
      this.redirectParams = res
    })
  }
  pwdForm: FormGroup = new FormGroup({
    username: new FormControl('', [Validators.required]),
    password: new FormControl('', [Validators.required]),
    frontVCode: new FormControl('')
  })

  vCodeForm: FormGroup = new FormGroup({
    phone: new FormControl('', [Validators.required, Validators.pattern(PHONE_REG)]),
    vCode: new FormControl('', [Validators.required])
  })


  rememberUser = false
  loginType = LoginTypeEnum.VERIFY_CODE

  // 切换登录方式
  switchLoginType(type: LoginTypeEnum){
    this.loginType = type

    if(type === LoginTypeEnum.PASSWORD){
      return
    }

    if(type === LoginTypeEnum.VERIFY_CODE){

      return
    }
    if(type === LoginTypeEnum.WE_CHAT){
      this.getWeChatCode()
      return
    }
  }

  //#region 密码登录
  frontVCodeValue = ''
  loginByPwd(){
    if(!formValid(this.pwdForm)){
      return
    }
    console.log(this.frontVCodeValue);
    console.log(this.frontVCode?.value);
    // 注释验证码
    if(this.frontVCodeValue.toLowerCase() !== this.frontVCode?.value){
      this.message.info('验证码不正确,请重新输入');
      (document.querySelector('#my-canvas') as HTMLCanvasElement).click()
      return
    }
    (document.querySelector('#my-canvas') as HTMLCanvasElement).click()

    this.submitLoading = true
    this.loginService._loginByPwd(this.username?.value, this.password?.value).subscribe({
      next: res => {
        console.log(res)
        this.afterLogin(res)
      }, 
      error: error => {
        this.message.createErrorMessage(error)
        this.submitLoading = false
      }
    })
  }
  //#endregion

  //#region 验证码登录
  loginByVCode(){
    if(!formValid(this.vCodeForm)){
      return
    }
    
    this.submitLoading = true
    this.loginService._loginByVCode(this.phone?.value, this.vCode?.value).subscribe(res => {
      this.afterLogin(res)
    }, error => {
      this.submitLoading = false
    })
    
  }
  //#endregion

  //#region 微信登录
  weChatLoginCode = ''
  wxCodeSpin = false
  wxCodeErr = false
  getWeChatCode(){
    this.wxCodeSpin = true
    this.wxCodeErr = false
    this.loginService._loginByWeChat().subscribe({
      next: (res) => {
        if(res && res.qrcodeUrl){
          this.weChatLoginCode = res.qrcodeUrl
          this.wxCodeSpin = false
          this.loginByWeChatWait(res.key)
        }else{
          this.wxCodeSpin = false
          this.wxCodeErr = true
        }
      },
      error: (error) => {
        this.wxCodeSpin = false
        this.wxCodeErr = true
      }
    })
  }
  loginByWeChatWait(key: string){
    this.loginService._loginByWeChatWait(key).subscribe({
      next: res => {
        console.log(res)
        if(res['authentication'] == 'success'){

        }else{
          this.wxCodeErr = true
        }
      },
      error: error => {
        this.wxCodeErr = true
      }
    })
  }
  //#endregion

  // 登录后
  afterLogin(res: any){
    if(res && (res.authentication === 'success' || res.message === 'success') ){
      this.message.success('登录成功')
      this.getUserInfo()
    }else if(res && res.error && res.error.message && res.error.message.indexOf('login has reached the limit') > -1){
      this.message.error('登录次数超过最大限制,请稍后再试')
    }else if(res && res.error && res.error.message && res.error.message.indexOf('not match')){
      this.message.error('用户名或密码不正确, 请重试')
    }else if(res && res.error && res.error.message){
      this.message.error(res.error.message)
    }else{
      this.message.error('登录失败')
    }
    this.submitLoading = false
  }

  //#region 忘记密码
  resetPwdVisible = false
  forgetPassword(){
    this.resetPwdVisible = true
  }
  //#endregion


  // 获取用户信息
  getUserInfo(){
    this.loginService._getUserInfo().subscribe((res: UserInfoData) => {
      if(res){
        this.userInfoService.setUserInfo(res)
        this.router.navigate([this.redirectUrl], { queryParams: this.redirectParams })
      }else{
        this.message.error('获取用户信息失败, 请重新登录')
        this.router.navigate(['/login'])
      }
    }, error => {
      this.message.error('获取用户信息失败, 请重新登录')
      this.router.navigate(['/login'])
    })
  }

  goHome(){
    this.router.navigate(['/home'])
    this.pwdForm.touched && this.pwdForm.errors
  }

  //#region 获取用户协议和隐私政策
  agreementTitle = ''
  userAgreementContent = ''
  userAgreementModal = false
  getUserAgreement(){
    this.userAgreementModal = true
    this.agreementTitle = '用户协议'
    this.commonService._getUserAgreement().subscribe({
      next: (res: any) => {
        if(res && res.agreementContent){
          console.log(res.agreementContent)
          this.userAgreementContent = res.agreementContent
        }else{
          this.message.error('获取用户协议失败,请重试')
        }
      },
      error: (error: any) => {
        this.message.createErrorMessage(error)
      }
    })
  }
  getPrivacyPolicies(){
    this.userAgreementModal = true
    this.agreementTitle = '隐私政策'
    this.commonService._getPrivacyPolicies().subscribe({
      next: (res: any) => {
        if(res && res.agreementContent){
          console.log(res.agreementContent)
          this.userAgreementContent = res.agreementContent
        }else{
          this.message.error('获取隐私政策失败,请重试')
        }
      },
      error: (error: any) => {
        this.message.createErrorMessage(error)
      }
    })
  }
  userAgreementOk(){
    this.userAgreementModal = false
  }
  //#endregion

  //#region get set
  get username(){
    return this.pwdForm.get('username')
  }
  get password(){
    return this.pwdForm.get('password')
  }
  get phone(){
    return this.vCodeForm.get('phone')
  }
  get vCode(){
    return this.vCodeForm.get('vCode')
  }
  get frontVCode(){
    return this.pwdForm.get('frontVCode')
  }
  //#endregion


  //#region 省统一身份认证登录
  goAuthentication(){
    location.href = environment.AUTH_LOGIN_URL
  }
  //#endregion
}

